#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2024/10/26 17:02
# @Author    :hzy
# @FileName  :截图.py
import uiautomator2 as u2
import numpy as np
import cv2, time
# python -m weditor


def my_screenshot(xy1, xy2, device, show=0, win_name="screenshot", color=cv2.COLOR_BGR2GRAY, thresh=127) -> np.ndarray:
    """
    :param xy1: 左上角坐标1
    :param xy2: 右下角坐标2
    :param device: 设备链接
    :param show: 是否展示
    :param win_name: 窗口名字
    :param color:返回格式（灰度or二值）
    :return: 根据提供的两个坐标进行截图后转换成灰度图（默认）
    """
    im = device.screenshot()
    num_img = np.asarray(im)
    gray = cv2.cvtColor(num_img, color)
    out = gray[xy1[1]:xy2[1], xy1[0]:xy2[0]]
    if show == 1:
        cv2.namedWindow(win_name, cv2.WINDOW_FREERATIO)
        cv2.imshow(win_name, out)
        cv2.waitKey()
    return out


def screen_find(A, B, template_way, device, num=10000000, sleep_time=0):
    # 加载模板图片
    template = cv2.imread(template_way, cv2.IMREAD_GRAYSCALE)
    min_loc, max_loc = (0, 0)
    max_val = 0
    while max_val < num:
        i = my_screenshot(A, B, device=device)
        res = cv2.matchTemplate(i, template, cv2.TM_CCOEFF)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        time.sleep(sleep_time)
        print(f"置信度：{max_val / 170000:.2f}%")
    return min_loc, max_loc


if __name__ == "__main__":
    d = u2.connect('127.0.0.1:16384')
    A = (1162, 140)
    B = (1218, 197)
    im = my_screenshot(A , B, d, show=1, win_name="test")
    cv2.imwrite("./test.jpg", im)
    i = screen_find(A, B, './test.jpg', device=d)
    print(i)
    pass
